<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/11/21
 * Time: 13:59
 */
namespace app\api\controller;
use think\Request;
use think\Db;
use app\api\service\UsercardService;
use app\api\service\OrderService;
require_once BASE_ROOT."core/application/api/controller/BaseController.php";
class Usercard extends BaseController
{
    /**
     * 会员卡详情
     */
    public function cardinfo(){
        $app_id = Request::instance()->param('i');       //小程序id
        $mch_id = $this->getMchId($app_id);
        $data = [
            'mch_id'  => $mch_id,
            'user_id'=>Request::instance()->param('uid')
        ];
        $rule = [
            ['mch_id','require','不存在商户'],
            ['user_id','require','未获取用户信息'],
        ];
        $result = $this->checkParam($rule,$data);
        if(!empty($result)){
            $rs['code'] = 1;
            $rs['msg'] = $result;
            return json_encode($rs);
        }
        $goods = new UsercardService();
        $info = $goods->get_cardinfo($data);
        return $info;
    }
    /**
     * 激活会员卡
     * @return string
     */
    public function addcard(){
        $rs = array('code' => 0,'info' => array());
        $app_id = Request::instance()->param('i');       //小程序id
        $mch_id = $this->getMchId($app_id);
        $data = [
            'mch_id'  => $mch_id,
            'user_id'=>Request::instance()->param('uid'),
            'mobile'=>Request::instance()->param('mobile',''),
            'name'=>Request::instance()->param('name',''),
        ];
        $rule = [
            ['mch_id','require','不存在商户'],
            ['user_id','require','未获取用户信息'],
            ['name','require','姓名不能为空'],
            ['mobile','require','手机号不能为空'],
        ];
        $result = $this->checkParam($rule,$data);
        if(!empty($result)){
            $rs['code'] = 1;
            $rs['msg'] = $result;
            return json_encode($rs);
        }
        $goods = new UsercardService();
        $info = $goods->get_addcard($data);
        return $info;
    }
    public function rechargemeal(){
        $app_id = Request::instance()->param('i');       //小程序id
        $mch_id = $this->getMchId($app_id);
        $data = [
            'mch_id'  => $mch_id,
            'user_id'=>Request::instance()->param('uid')
        ];
        $rule = [
            ['mch_id','require','不存在商户'],
            ['user_id','require','未获取用户信息'],
        ];
        $result = $this->checkParam($rule,$data);
        if(!empty($result)){
            $rs['code'] = 1;
            $rs['msg'] = $result;
            return json_encode($rs);
        }
        $goods = new UsercardService();
        $info = $goods->get_rechargemeal($data);
        return $info;
    }
    public function createOrder()
    {
        $rs = array('code' => 0,'info' => array());
        $app_id = Request::instance()->param('i');       //小程序id
        $mch_id = $this->getMchId($app_id);
        $data = [
            'mch_id'  => $mch_id,
            'payprice' =>  Request::instance()->param('payprice',0),
            'giveprice' =>  Request::instance()->param('giveprice',0),
            'card_id' =>  Request::instance()->param('card_id'),
            'openid' => Request::instance()->param('openid'),
            'integral' => Request::instance()->param('integral',0)
        ];
        $rule = [
            ['mch_id','require','不存在商户'],
            ['openid','require','未获取用户信息'],
            ['card_id','require','未获取用户信息'],
        ];
        $result = $this->checkParam($rule,$data);
        if(!empty($result)){
            $rs['code'] = 1;
            $rs['msg'] = $result;
            return json_encode($rs);
        }
        $time = time();
        $openid=$data['openid'];
        unset($data['openid']);
        $data['ispay']=0;
        $data['payprice']=round(floatval($data['payprice']) ,2);
        $data['create_time'] = $time;
        $data['order_no']=$this->createOrderNo();
        $data['out_trade_no']=$this->createOutTradeNo();
        // 启动事务
        Db::startTrans();
        try {
            $id=Db::name('ybsc_user_card_orders')->strict(true)->insertGetId($data);
            //创建支付订单
            $pay_data = array(
                'out_trade_no'  => $data['out_trade_no'],
                'pay_type'  => Request::instance()->param('pay_type','1'),
                'type_alis_id'  => $id,
                'pay_body'      => "平台支付",
                'pay_detail'    => "会员卡充值",
                'pay_money'     => $data['payprice'],
                'create_time'   => $time
            );
            Db::name('ybsc_user_card_payment')->insert($pay_data);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $id = 0;
            Db::rollback();
        }
        if(empty($id))
        {
            $rs['code'] = 1;
            $rs['msg'] = "充值失败";
            return json_encode($rs);
        }
        if(!empty($pay_data))
        {
            //存应用id
            $GLOBALS['mch_id'] = $mch_id;
            //初始化值对象
            $input = new \WxPayUnifiedOrder();
            $input->SetBody($pay_data['pay_body']);
            $input->SetOpenid($openid);
            $input->SetDetail($pay_data['pay_detail']);
            $input->SetTotal_fee($pay_data['pay_money']*100);
            $input->SetOut_trade_no($pay_data['out_trade_no']);
            $input->SetTrade_type("JSAPI");
            global $_W;
            $notice_url = $_W['siteroot']."addons/yb_shop/core/pay_card.php";
            $input->SetNotify_url($notice_url);
            // 向微信统一下单，并返回 unifiedorder，它是一个array数组
            $unifiedorder = \WxPayApi::unifiedOrder($input);
            //下单错误
            if($unifiedorder['return_code'] == "FAIL")
            {
                $rs['code'] = 1;
                $rs['msg'] = $unifiedorder['return_msg'];
                exit(json_encode($rs,true));
            }
            if($unifiedorder['result_code'] == "FAIL")
            {
                $rs['code'] = 1;
                $rs['msg'] = $unifiedorder['err_code_des'];
                exit(json_encode($rs,true));
            }
            Db::name('ybsc_user_card_orders')->where('out_trade_no', $data['out_trade_no'])->update(['prepay_id' => $unifiedorder['prepay_id']]);
            $res =  $this->weixinapp($unifiedorder);
            $pay_info = array();
            foreach ($this->objectArray($res) as $value)
            {
                $pay_info = $value;
            }
            $pay_info['paySign'] = $pay_info['sign'];
            unset($pay_info['sign']);
            $rs['info'] = $pay_info;
            return json_encode($rs);
        }
        else
        {
            $rs['code'] = 1;
            $rs['msg'] = "生成订单失败";
            return json_encode($rs);
        }
    }
    /**
     * 返回小程序需要的数据
     * @param $unifiedorder
     * @return \WxPayJsApiPay
     */
    private function weixinapp($unifiedorder) {
        $input = new \WxPayJsApiPay();
        $input->SetAppid($unifiedorder['appid']);
        $input->SetTimeStamp( '' . time() . '');
        $input->SetNonceStr($this->createNoncestr());
        $input->SetPackage('prepay_id=' . $unifiedorder['prepay_id']);
        $input->SetSignType("MD5");
        $input->SetSign();
        return $input;
    }
    //作用：产生随机字符串，不长于32位
    private function createNoncestr($length = 32) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    public function consumeLog()
    {
        $rs = array('code' => 0,'info' => array());
        $uid = Request::instance()->param('uid');
        $page = Request::instance()->param('page',1);
        $app_id = Request::instance()->param('i');       //小程序id
        $mch_id = $this->getMchId($app_id);
        $rule = [
            ['buyer_id','require','uid不能为空'],
            ['mch_id','require','不存在商户'],
        ];
        $data = [
            'buyer_id'  => $uid,
            'mch_id'  => $mch_id,
        ];
        $result = $this->checkParam($rule,$data);
        if(!empty($result)){
            $rs['code'] = 1;
            $rs['msg'] = $result;
            return json_encode($rs);
        }
        $order  = new OrderService();
        $data['pay_type']=2;
        $info = $order->orderList($data,$page);
        $rs['info'] = $info;
        return json_encode($rs);
    }
    /**
     * 充值记录
     * @return string
     */
    public function exchangelog(){
        $rs = array('code' => 0,'info' => array());
        $app_id = Request::instance()->param('i');       //小程序id
        $page = Request::instance()->param('page',1);
        $mch_id = $this->getMchId($app_id);
        $data = [
            'mch_id'  => $mch_id,
            'card_id'=>Request::instance()->param('card_id')
        ];
        $rule = [
            ['mch_id','require','不存在商户'],
            ['card_id','require','未获取用户信息'],
        ];
        $result = $this->checkParam($rule,$data);
        if(!empty($result)){
            $rs['code'] = 1;
            $rs['msg'] = $result;
            return json_encode($rs);
        }
        $goods = new UsercardService();
        $info = $goods->get_exchangelog($data,$page);
        $rs['info']=$info;
        return json_encode($rs);
    }

}